package com.example.mymvvmdemo.models.main.fragment.home;

import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager2.widget.ViewPager2;

import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.base.BaseLoadFragment;
import com.example.mymvvmdemo.constants.UrlConstants;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.databinding.FragmentHomeBinding;
import com.example.mymvvmdemo.entity.CommonEntity;
import com.example.mymvvmdemo.entity.FailEntity;
import com.example.mymvvmdemo.models.main.MainViewModel;
import com.example.mymvvmdemo.models.main.fragment.home.adapter.BannerAdapter;
import com.example.mymvvmdemo.models.main.fragment.home.adapter.HomeAdapter;
import com.example.mymvvmdemo.models.main.fragment.home.entity.BlogArticlesEntity;
import com.example.mymvvmdemo.net.presenter.GetPresenter;
import com.example.mymvvmdemo.net.view.IView;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.ToastUtils;

import java.util.HashMap;
import java.util.List;


public class HomeFragment extends BaseLoadFragment<FragmentHomeBinding> implements IView.GetView, HomeAdapter.HomeListener {

    private MainViewModel mainViewModel;
    private GetPresenter getPresenter;
    private BannerAdapter bannerAdapter;
    private Handler handler;
    private Runnable bannerRunnable;
    private HomeAdapter homeAdapter;


    @Override
    protected void initData() {
        getPresenter = new GetPresenter(this);
        handler = new Handler(Looper.getMainLooper());
        initBannerAdapter();
        initAdapter();
        startLoadData();
    }

    @Override
    protected void initListener() {
        binding.refreshViewShowContent.setOnRefreshListener(relayout -> {
            mainViewModel.isRefresh = true;
            startLoadData();
        });
        binding.refreshViewShowContent.setOnLoadMoreListener(relayout -> {
            //当前不需要分页加载，后续再加
//            mainViewModel.isRefresh = false;
            startLoadData();
        });

        // 设置页面切换监听
        binding.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                updateIndicators(position);
                // 页面切换后重置定时器
                resetAutoScroll();
            }
        });

        binding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchArticle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        // 设置触摸监听
        binding.viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mainViewModel.isUserTouching = true;
                        stopAutoScroll();
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        mainViewModel.isUserTouching = false;
                        startAutoScroll();
                        break;
                }
                return false;
            }
        });
    }


    /*************************************自定义方法*********************************************/
    public void setMainViewModel(MainViewModel mainViewModel) {
        this.mainViewModel = mainViewModel;
    }

    public void showNoDataView() {
        int dataListSize = homeAdapter.getDataListSize();
        binding.includeNoData.ivNoData.setVisibility(dataListSize == 0 ? View.VISIBLE : View.GONE);
    }

    private void searchArticle(String s) {
        int length = s.length();
        if (length == 0) {
            homeAdapter.setDataList(mainViewModel.homeList);
        } else {
            mainViewModel.searchList.clear();
            for (int i = 0; i < mainViewModel.homeList.size(); i++) {
                BlogArticlesEntity.DataDTO dataDTO = mainViewModel.homeList.get(i);
                String title = dataDTO.getTitle();
                if (title.contains(s)) {
                    mainViewModel.searchList.add(dataDTO);
                }
            }
            homeAdapter.setDataList(mainViewModel.searchList);
        }
        showNoDataView();
    }

    public void startLoadData() {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        getPresenter.startLoadGet(UrlConstants.blogArticles, hashMap, UrlTypeConstants.blogArticles);
    }

    private void deviceComplete() {
        try {
            binding.refreshViewShowContent.finishRefresh();
            binding.refreshViewShowContent.finishLoadMore();
            homeAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            LogUtils.e("deviceComplete error:" + e.getMessage());
        }
    }


    private void initAdapter() {
        homeAdapter = new HomeAdapter(getContext(), mainViewModel.homeList);
        homeAdapter.setListener(this);
        binding.recyclerView.setAdapter(homeAdapter);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }

    private void initBannerAdapter() {
        bannerAdapter = new BannerAdapter(mainViewModel.bannerImages);
        binding.viewPager.setAdapter(bannerAdapter);
        binding.viewPager.setOffscreenPageLimit(1);
        // 添加指示器
        setupIndicators(mainViewModel.bannerImages.size());
    }

    private void setupIndicators(int count) {
        ImageView[] indicators = new ImageView[count];
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(8, 0, 8, 0);

        for (int i = 0; i < count; i++) {
            indicators[i] = new ImageView(requireContext());
            indicators[i].setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.indicator_inactive_background));
            indicators[i].setLayoutParams(params);
            binding.indicatorContainer.addView(indicators[i]);
        }
        updateIndicators(0);
    }

    private void updateIndicators(int position) {
        int count = binding.indicatorContainer.getChildCount();
        for (int i = 0; i < count; i++) {
            ImageView indicator = (ImageView) binding.indicatorContainer.getChildAt(i);
            indicator.setImageDrawable(ContextCompat.getDrawable(requireContext(), i == position ? R.drawable.indicator_active_background : R.drawable.indicator_inactive_background));
        }
    }

    private void startAutoScroll() {
        if (!mainViewModel.isUserTouching) {
            stopAutoScroll();
            bannerRunnable = new Runnable() {
                @Override
                public void run() {
                    if (!mainViewModel.isUserTouching) {
                        int currentItem = binding.viewPager.getCurrentItem();
                        int nextItem = (currentItem + 1) % bannerAdapter.getItemCount();
                        binding.viewPager.setCurrentItem(nextItem);
                    }
                }
            };
            handler.postDelayed(bannerRunnable, mainViewModel.BANNER_DELAY);
        }
    }

    private void stopAutoScroll() {
        if (handler != null && bannerRunnable != null) {
            handler.removeCallbacks(bannerRunnable);
        }
    }

    private void resetAutoScroll() {
        stopAutoScroll();
        startAutoScroll();
    }

    /**************************************适配器回调***********************************************/
    @Override
    public void onHomeClick(int position) {
        BlogArticlesEntity.DataDTO dataDTO = homeAdapter.getDataList().get(position);
        int id = dataDTO.getId();
        mainViewModel.startArticleDetailActivity(getActivity(), id);
    }

    /**************************************自定义方法***********************************************/
    @Override
    public void loadGetSuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.blogArticles)) {
            loadBlogArticlesSuccess(result, code);
        }
    }

    @Override
    public void loadGetFail(String message, String type) {
        if (type.equals(UrlTypeConstants.blogArticles)) {
            loadBlogArticlesFail();
        }
    }

    @Override
    public void loadGetAccountError(int code) {

    }

    @Override
    public void loadGetNetWorkError() {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    /**************************************处理请求后数据***********************************************/
    private void loadBlogArticlesSuccess(String result, int code) {

        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            loadBlogArticlesFail();
            return;
        }

        try {
            BlogArticlesEntity blogArticlesEntity = gson.fromJson(result, BlogArticlesEntity.class);
            List<BlogArticlesEntity.DataDTO> data = blogArticlesEntity.getData();

            if (data == null) {
                loadBlogArticlesFail();
                return;
            }
            if (data.size() == 0) {
                loadBlogArticlesFail();
                return;
            }
            if (mainViewModel.isRefresh) {
                mainViewModel.homeList.clear();
            }
            mainViewModel.homeList.addAll(data);
            homeAdapter.notifyDataSetChanged();
            showNoDataView();
            deviceComplete();

        } catch (Exception e) {
            loadBlogArticlesFail();
        }
    }

    private void loadBlogArticlesFail() {
        deviceComplete();
        dismissDialog();
        showNoDataView();
    }

    /**************************************生命周期***********************************************/
    @Override
    public void onPause() {
        super.onPause();
        stopAutoScroll();
    }

    @Override
    public void onResume() {
        super.onResume();
        startAutoScroll();
    }


}
